package com.gao.alg.geek;

import java.util.HashMap;
import java.util.Map;

public class TwoSum {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int i1 = i+1; i1 < nums.length; i1++) {
                int ret = nums[i] + nums[i1];
                if (ret == target){
                    return  new int[]{i,i1};
                }
            }
        }
        throw new IllegalArgumentException();
    }

    /**
     * 哈希
     * a + b = target
     * a = target - b
     * @param nums
     * @param target
     * @return
     */
    private Map<Integer,Integer> map = new HashMap<>();
    public int[] twoSumWithHash(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target-nums[i])){
                return new int[]{i,map.get(target-nums[i])};
            }else {
                map.put(nums[i],i);
            }
        }
        throw new IllegalArgumentException();
    }
}
